package threadDemo;

/**
 * @author Ajie
 * @date 1/7/25
 * @function
 */
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicByte {
    private final AtomicInteger value;

    // 构造函数，初始化为0
    public AtomicByte() {
        this((byte) 0);
    }

    // 构造函数，初始化为指定值
    public AtomicByte(byte initialValue) {
        this.value = new AtomicInteger(initialValue);
    }

    // 获取当前值
    public byte get() {
        return (byte) value.get();
    }

    // 设置新值
    public void set(byte newValue) {
        value.set(newValue);
    }

    // 原子自增，并返回旧值
    public byte getAndIncrement() {
        while (true) {
            int current = value.get();
            byte currentByte = (byte) current;
            byte nextByte = (byte) (currentByte + 1);
            if (currentByte == Byte.MAX_VALUE) {
                nextByte = Byte.MIN_VALUE;
            }
            int next = nextByte;
            if (value.compareAndSet(current, next)) {
                return currentByte;
            }
        }
    }

    @Override
    public String toString() {
        return Byte.toString(get());
    }
}